from django.shortcuts import render
from django.http import HttpResponse, HttpResponseRedirect
from django.template import loader, RequestContext
from .models import BookInfo, PeopleInfo
from django.db.models import F, Q


# Create your views here.


def index(request):
    # return HttpResponse("hello world")
    content = {'title': "世界你好"}
    return render(request, "index.html", content)


def index1(request):
    # return HttpResponse("hello world")
    content = {'title': "世界你好"}
    return render(request, "index1.html", content)


def demo_template(request):
    """使用模板文件"""
    context = {'title': "世界你好", 'name': 'ak', 'knowledge': ['java', 'python', 'scala', 'c', 'c++']}
    return render(request, "book/demo_template.html", context)


def demo_database(request):
    """
    使用数据库
        返回列表的过滤器如下：
            all()：返回所有的数据
            filter()：返回满足条件的数据
            exclude()：返回满足条件之外的数据，相当于sql语句中where部分的not关键字
            order_by()：返回排序后的数据
        返回单个对象的过滤器如下：
            get()：返回单个满足条件的对象
            如果未找到会引发"模型类.DoesNotExist"异常
            如果多条被返回，会引发"模型类.MultipleObjectsReturned"异常
            count()：返回当前查询的总条数
            aggregate()：聚合
            exists()：判断查询集中是否有数据，如果有则返回True，没有则返回False

        模型对象的属性与常量值比较，两个属性怎么比较呢？使用F对象
            1.查询阅读量大于评论量的书籍
            bookInfos = BookInfo.books.filter(readcount__gt=F('commentcount'))

        Q对象:多个过滤器逐个调用表示逻辑与关系，同sql语句中where部分的and关键字
            bookInfos = BookInfo.books.filter(readcount__gt=20,id__lt=3)
            或
            bookInfos = BookInfo.books.filter(readcount__gt=20).filter(id__lt=3)

            1.查询阅读量大于20，或编号小于3的图书
            bookInfos = BookInfo.books.filter(Q(readcount__gt=20) | Q(id__lt=3))

        聚合函数
            使用aggregate()过滤器调用聚合函数，返回单个对象
            聚合函数包括：Avg，Max，Min，Sum，Count

            readcount = BookInfo.books.aggregate(Sum('readcount'))

        关联查询
            # 先查编号为1的书
            book = BookInfo.books.get(pk=1)
            # 再通过关联查询到编号为1的书里面的人物信息
            peopleInfos = book.peopleinfo_set.all()

        自关联
            peopleInfos = PeopleInfo.objects.filter(book__name='天龙八部')
            bookInfos = BookInfo.books.filter(peopleinfo__description__contains='降龙')

    """
    book_list = BookInfo.objects.all()
    print(BookInfo.objects.get(id=1))
    print(BookInfo.objects.filter(name__contains="雪山"))
    print(BookInfo.objects.filter(name__endswith="八部"))
    print(BookInfo.objects.filter(name__isnull=False))
    print(BookInfo.objects.filter(name__in=['学习']))
    print(BookInfo.objects.filter(id__gt=1))

    author_list = PeopleInfo.objects.all().order_by('id')

    return render(request, "book/demo_database.html", {'book_list': book_list, 'author_list': author_list})


def demo_add(request):
    """新增"""
    book = BookInfo()
    book.name = "雪山飞狐"
    book.save()

    return HttpResponseRedirect("/demo_database")


def demo_delete(request, bid):
    """删除"""
    print(request)
    book = BookInfo.objects.get(id=bid)
    book.delete()

    return HttpResponseRedirect("/demo_database")
